<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div ref="ele">
        <!-- 搜索 -->
        <label class="el-form-item-label">煤炭名称</label>
        <el-input v-model="query.coalName" clearable placeholder="煤炭名称" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">煤炭种类</label>
        <el-select v-model="query.coalCategoryId" filterable placeholder="请选择" clearable @change="crud.toQuery" style="width: 185px;" class="filter-item">
          <el-option
            v-for="item in coalTypes"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
        <label class="el-form-item-label">创建日期</label>
        <date-range-picker v-model="query.createTime" class="date-item" />
        <rrOperation :crud="crud" />
      </div>
      <crudOperation :permission="permission" >
        <el-button
          slot="right"
          class="filter-item"
          type="success"
          icon="el-icon-edit"
          size="mini"
          :loading="syncLoading"
          :disabled="crud.selections.length === 0"
          v-permission="['merchantCoal:edit']"
          @click="edit()">修 改</el-button>
      </crudOperation>
      <el-dialog
        v-dialogDrag
        :show-close='false'
        class="transferDialog"
        v-if="crud.status.cu > 0"
        :close-on-click-modal="false"
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="form.falg ? '详情' : crud.status.title"
        width="900px">
        <vue-scroll >
          <el-form ref="form" :model="form" :rules="rules" size="mini">
            <el-card class="box-card">
              <el-row :gutter="24">
                <el-col :span="8">
                  <el-form-item label="矿口" prop="mineMouthId" label-width="110px">
                    <el-select  v-model="coalValueData.mineMouthId" :disabled="true" size="mini" @change="selectMineMouthName(coalValueData.mineMouthId)"  filterable clearable placeholder="请选择矿口" >
                      <el-option
                        v-for="item in options"
                        :key="item.id"
                        :label="item.mineMouthName"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="煤种" prop="coalCategoryId" label-width="110px">
                    <el-select v-model="coalValueData.coalCategoryId" :disabled="true" size="mini" filterable clearable placeholder="请选择" @change="selectCategoryCode(coalValueData.mineMouthId,coalValueData.coalCategoryId)">
                      <el-option
                        v-for="item in coalType"
                        :key="item.coalCategoryId"
                        :label="item.coalCategoryName"
                        :value="item.coalCategoryId">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="煤炭名称" prop="coalName" label-width="110px">
                    <el-select v-model="coalValueData.coalName" size="mini" :disabled="true" filterable clearable placeholder="请选择煤炭名称" @change="selectCategoryCodeName(coalValueData.mineMouthId,coalValueData.coalCategoryId,coalValueData.coalName)">
                      <el-option
                        v-for="item in coalName"
                        :key="item.name"
                        :label="item.name"
                        :value="item.name">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

            </el-card>

            <el-card style="background-color: #dfe4ed;border-radius: 30px"  v-if="this.coalData">
              <el-row :gutter="24" style="margin: 5px 50px">
                <el-col :span="6" style="margin: 10px 0">
                  <span style="border-radius: 30px">煤矿价格: {{coalData.coalPrice}}{{coalData.priceUnit}}</span>
                </el-col>
                <el-col :span="6" style="margin: 10px 0">
                  <span style="border-radius: 30px">工艺: {{coalData.coalTechnologyName}}</span>
                </el-col>
                <el-col :span="6" style="margin: 10px 0">
                  <span style="border-radius: 30px">发热量: {{coalData.coalCalorific}}{{'Kcal/kg'}}</span>
                </el-col>
                <el-col :span="6" style="margin: 10px 0">
                  <span style="border-radius: 30px">含硫量: {{coalData.allSulphur}}{{'%'}}</span>
                </el-col>

                <el-col :span="6" style="margin: 10px 0">
                  <span style="border-radius: 30px">水分: {{coalData.wholeWater}}{{'%'}}</span>
                </el-col>

                <el-col :span="6" style="margin: 10px 0">
                  <span style="border-radius: 30px">灰分: {{coalData.serchHuifen}}{{'%'}}</span>
                </el-col>

                <el-col style="margin: 10px 0" :span="6" v-for="(item,index) in coalData.coalInfo" :key="index">
                  <span style="border-radius: 30px">{{item.coalName}}: {{item.value == null ? '-': item.value}}</span>
                </el-col>
              </el-row>
              <!--<el-row :gutter="24">
                <el-col :span="5" v-for="(item,index) in coalData.coalInfo" :key="index">
                  <el-form-item :label="item.coalName" label-width="110px">
                    <span style="border-radius: 30px">{{item.value == null ? '-': item.value}}{{'%'}}</span>
                  </el-form-item>
                </el-col>
              </el-row>-->
            </el-card>
            <el-card class="box-card">
              <div slot="header">
                <span>基本信息</span>
              </div>
              <el-row :gutter="25">
                <el-col :span="8">
                  <el-form-item label="工艺" prop="coalTechnologyCode" label-width="110px">
                    <el-select v-model="form.coalTechnologyCode" size="mini" filterable clearable placeholder="请选择工艺" @change="selectCoalTechnology(form.coalTechnologyCode)">
                      <el-option
                        v-for="item in coalTechnology"
                        :key="item.ecode"
                        :label="item.cname"
                        :value="item.ecode">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="发热量" prop="coalCalorific" label-width="110px">
                    <el-input v-model="form.coalCalorific" clearable size="mini" placeholder="发热量">
                      <template slot="append">Kcal/kg</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="含硫量" prop="allSulphur" label-width="110px">
                    <el-input v-model="form.allSulphur" clearable size="mini" placeholder="含硫量">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="水分" prop="wholeWater" label-width="110px">
                    <el-input v-model="form.wholeWater" clearable size="mini" placeholder="水分">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="灰分" prop="serchHuifen" label-width="110px">
                    <el-input v-model="form.serchHuifen" clearable size="mini" placeholder="灰分">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8" v-for="(item, index) in baseCates" :key="index">
                  <el-form-item :label="item.cname" :prop="item.ecode" label-width="110px">
                    <el-input
                      v-model="form.coalInfos[item.ecode]"
                      size="mini"
                      clearable
                      :placeholder="item.cname">
                      <template slot="append" v-if="item.ecode ==='crc'">{{''}}</template>
                      <template slot="append" v-else-if="item.ecode ==='high_order'">{{'KCal/kg'}}</template>
                      <template slot="append" v-else-if="item.ecode ==='low_order'">{{'KCal/kg'}}</template>
                      <template slot="append" v-else >{{'%'}}</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>
            <el-card class="box-card">
              <div slot="header">
                <span>煤炭信息</span>
              </div>
              <el-row :gutter="24">
                <el-col :span="8">
                  <el-form-item label="销售价格" prop="sellPrice" label-width="110px">
                    <el-input v-model="form.sellPrice" clearable size="mini" placeholder="价格" >
                      <template slot="append">{{this.priceUnit}}</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="煤炭数量" prop="coalNumber" label-width="110px">
                    <el-input  v-model.number="form.coalNumber" clearable size="mini" placeholder="煤炭数量" >
                      <template slot="append">{{'吨'}}</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="最低购买数量" prop="lowNumber" label-width="110px">
                    <el-input  v-model.number="form.lowNumber" clearable size="mini" placeholder="最低购买数量" >
                      <template slot="append">{{'吨'}}</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="24">
                <el-col :span="8">
                  <el-form-item label="化验时间" prop="laboratoryTime" label-width="110px">
                    <el-date-picker
                      style="width: 160px"
                      value-format="yyyy-MM-dd"
                      v-model="form.laboratoryTime"
                      type="date"
                      placeholder="选择日期">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="16">
                  <el-form-item label="化验单位" prop="laboratoryCompany" label-width="110px">
                    <el-input  v-model="form.laboratoryCompany" clearable size="mini" placeholder="请输入化验单位" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="24">
                <el-col :span="8">
                  <el-form-item label="煤炭图片" prop="coalPic" label-width="110px">
                    <oss-upload :limit='1' notMust= "true" :echodisplaylist="form.coalPics" ref="upload1" :type="'COAL_IMG'" :customVal="{imgName:'form.imgName'}" v-on:success="update"></oss-upload>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="化验单图片" prop="laboratoryBillPic" label-width="110px">
                    <oss-upload :limit='1' notMust= "false" :echodisplaylist="form.laboratoryBillPics" ref="upload" :type="'LABORATORY_BILL_IMG'" :customVal="{imgName:'form.imgName'}" v-on:success="save"></oss-upload>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>
          </el-form>
        </vue-scroll >
        <div slot="footer" class="dialog-footer">
          <el-button size="mini" @click="crud.cancelCU">取 消</el-button>
          <el-button :loading="crud.cu === 2" v-if = "!form.falg" type="success" @click="update1(false)">保存</el-button>
         <!-- <el-button :loading="crud.cu === 2" v-if = "!form.falg" type="primary" @click="update1(true)">保存并发布</el-button>-->
        </div>
      </el-dialog>
    </div>

    <!--表格渲染-->
    <el-table
      :height="tableHeight"
      ref="table"
      border
      :v-loading="crud.loading"
      :data="crud.data"
      style="width: 100%;"
      @selection-change="crud.selectionChangeHandler"
      :summary-method="getCommSummaries({customer: crud.totalObject, titleIndex: 0})"
      :show-summary="true" >
      <el-table-column type="selection" width="60" align="center"/>
      <el-table-column prop="coalName"  width="100" align="center" label="煤炭名称" show-overflow-tooltip />
      <el-table-column prop="coalCategoryName" width="90" label="煤炭种类" show-overflow-tooltip align="center"/>
      <el-table-column prop="mineMouthName" width="140" label="所属煤矿名称" show-overflow-tooltip align="center"/>
      <el-table-column prop="sellPrice" width="90" label="销售价格" show-overflow-tooltip align="center">
        <template slot-scope="scope">
          <span class="search-text1">{{scope.row.sellPrice + scope.row.priceUnit}}</span>
        </template>
      </el-table-column>
      <!--<el-table-column prop="coalPrice" width="90" label="煤炭价格" show-overflow-tooltip>
        <template slot-scope="scope">
           <span class="search-text1">{{scope.row.coalPrice | nullFilter}}
             {{scope.row.priceUnit}}</span>
        </template>
      </el-table-column>-->
      <el-table-column prop="coalNumber" width="110" label="煤炭数量（吨）" show-overflow-tooltip align="center"/>
      <el-table-column prop="lowNumber" width="130" label="最低购买数量（吨）" show-overflow-tooltip align="center"/>
      <el-table-column prop="isShow" header-align="center" align="center" width="110"  label="是否上下架">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.isShow === 0 ? '点击上架' : '点击下架'"  placement="top">
            <el-button type="info" size="mini" @click="updatePublish(scope.row.id, true)" v-if="scope.row.isShow === 0">下架</el-button>
            <el-button type="success" size="mini" @click="updatePublish(scope.row.id, false)" v-if="scope.row.isShow === 1">上架</el-button>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="issueStatus" width="90" show-overflow-tooltip label="状态" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.issueStatus === 1 ? 'success' : 'warning'">
            {{ scope.row.issueStatus === 0 ? '未发布' :
               scope.row.issueStatus === 1 ? '审核中' :
               scope.row.issueStatus === 2 ? '已发布' : '-'
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="issueTime" show-overflow-tooltip width="150" label="发布时间">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.issueTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="coalTechnologyName" align="center" show-overflow-tooltip width="100" label="工艺" />
      <el-table-column prop="coalCalorific" align="center" show-overflow-tooltip width="100" label="发热量" />
      <el-table-column prop="allSulphur" align="center" show-overflow-tooltip width="100" label="含硫量" />
      <el-table-column prop="wholeWater" align="center" show-overflow-tooltip width="100" label="水分" />
      <el-table-column prop="serchHuifen" align="center" show-overflow-tooltip width="100" label="灰分" />
      <el-table-column label="基本信息" width="100" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-popover trigger="click" placement="top" width="600">
            <el-row :gutter="24">
              <el-col :span="8" v-for="(item,index) in scope.row.merchantCoalInfos" :key="index">
                <p><el-tag size="medium">{{ item.coalName }}</el-tag> : {{ item.value }}{{item.value !== null ? '%': '-'}}</p>
              </el-col>
            </el-row>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">基本信息</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="laboratoryTime" show-overflow-tooltip width="130" label="化验时间">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.laboratoryTime,'{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="laboratoryCompany" show-overflow-tooltip width="180" label="化验单单位">
        <template slot-scope="scope">
          {{scope.row.laboratoryCompany | nullFilter }}
        </template>
      </el-table-column>
      <el-table-column prop="level" width="90" align="center" label="推荐位置" show-overflow-tooltip>
        <template slot-scope="scope">
          {{scope.row.level === 1 ? '优质' : scope.row.level === 2 ? '推荐' : '默认'}}
        </template>
      </el-table-column>
      <el-table-column prop="createBy" show-overflow-tooltip label="创建人" />
      <el-table-column prop="createTime" width="150" show-overflow-tooltip label="创建时间">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime,'{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="150px" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" v-permission="['merchantCoal:edit']" icon="el-icon-edit"  @click="edit(scope.row)"></el-button>
        </template>
      </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
</template>

<script>
import CRUD, { header, form, presenter } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import pagination from '@crud/Pagination'
import DateRangePicker from '@/components/DateRangePicker/index'
import OssUpload from '@/components/oss-upload/oss-upload.vue'
import crudCommodity from '@/api/commodity/commodity'

const defaultForm = {sellPrice: null,merchantCoalId: null,laboratoryBillPics: null,coalPics: null,coalInfos: [],mineMouthName: null,coalInfo: [],id: null,coalName: null,price: null,mineMouthId:null,
  merchantId: null,priceUnit: null,merchantName: null,coalCalorific: null,allSulphur: null,wholeWater: null,serchHuifen: null,coalCategoryName: null,coalCategoryId: null,coalTechnologyName: null,coalTechnologyCode: null,
  laboratoryTime: null,laboratoryBillPic: null,laboratoryCompany: null,remark: null,isShow: null,status: null,sellTime: null,
  createBy: null, createTime: null,updateBy: null,updateTime: null}

export default {
  name: 'AwaitingRelease',
  components: { pagination, crudOperation, rrOperation, DateRangePicker, OssUpload },
  mixins: [presenter(), header(), form(defaultForm)],
  cruds() {
    return CRUD({ title: '煤炭销售', url: 'api/commodity/awaitingList', query: { status: [2] }, idField: 'id', sort: 'id,desc', crudMethod: { ...crudCommodity }})
  },
  data() {
    return {
      height: this.getTableHeight({}),
      tableHeight: this.height,
      syncLoading: false,
      dialogFormVisible: false,
      echodisplaylist: [],
      operationVisible: false,
      operationValue: {},
      operationLoading: false,
      fullscreenLoading: false,
      issue: false,
      options: [],
      coalType: [],
      coalTypes: [],
      coalName: [],
      merchant: [],
      coalTechnology: [],
      baseCates: [],
      coalData: null,
      coalValueData: {},
      status: [
        { key: '已发布', value: 1 },
        { key: '未发布', value: 0 }
      ],
      priceUnit: '',
      baseCatesValue: [],
      forms: {
        coalInfos: []
      },
      rules: {
        mineMouthId: [
          { required: true, message: '矿口不能为空', trigger: 'blur' }
        ],
        coalNumber: [
          { required: true, message: '煤炭数量不能为空', trigger: 'blur' }
        ],
        coalName: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ],
        coalCategoryId: [
          { required: true, message: '煤种不能为空', trigger: 'blur' }
        ],
        coalCalorific: [
          { required: true, message: '发热量不能为空', trigger: 'blur' }
        ],
        allSulphur: [
          { required: true, message: '含硫量不能为空', trigger: 'blur' }
        ],
        wholeWater: [
          { required: true, message: '水分不能为空', trigger: 'blur' }
        ],
        serchHuifen: [
          { required: true, message: '灰分不能为空', trigger: 'blur' }
        ],
        coalTechnologyCode: [
          { required: true, message: '工艺不能为空', trigger: 'blur' }
        ],
        sellPrice: [
          { required: true, message: '销售价格不能为空', trigger: 'blur' },
          { type: 'number', message: '请输入数字', trigger: 'blur', transform(value) {
            return Number(value)
          }}
        ]
      },
      operationRules: {
        isShow: [
          { required: true, message: '是否显示', trigger: 'blur' }
        ],
        level: [
          { required: true, message: '等级', trigger: 'blur' }
        ]
      },
      permission: {
        operation: ['merchantCoal:operation'],
        add: ['merchantCoal:add'],
        edit: ['merchantCoal:edit'],
        del: ['commodity:del']
      }
    }
  },

  created() {
    this.crud.optShow = {
      reset: true,
      add: false,
      edit: false,
      del: false,
      download: false
    }
  },
  methods: {
    updatePublish (id, value) {
      let data = {
        id: id,
        falg: value
      }
      this.updateStatus(data)
    },
    updateStatus (data) {
      let self = this
      self.$http.put('/api/commodity/isShow', data).then(function (res) {
        if (res.ok) {
          self.$message.success(value ? '上架成功' : '下架成功')
          // 刷新
          self.crud.toQuery()
        } else {
          self.$message.error(data.msg)
          self.crud.toQuery()
        }
      }).catch(function (error) {
        self.crud.toQuery()
        console.log(error)
      })
    },
    issueCoal() {
      let self = this
      const issueId = []
      let updateData = self.crud.selections
      if (updateData.length < 1) {
        self.$message({
          message: '请选择一行数据',
          type: 'warning'
        })
      } else {
        updateData.forEach(d => {
          if (0 === d.issueStatus) {
            issueId.push(d.id)
          }
        })
        if (issueId.length === 0){
          this.$message({
            showClose: true,
            message: '请选择未发布的煤炭商品',
            type: 'error'
          });
          return
        }
        let msg = ''
        if(issueId.length != updateData.length){
          msg = '（只会发布未发布的煤炭商品）'
        }
        this.$confirm(msg + `确认发布选中的数据吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.issueMethod(updateData)
        }).catch(() => {})

      }
    },
    issueMethod(key, index) {
      let self = this
      const ids = []
      key.forEach(d => {
        ids.push(d.id)
      })
      self.syncLoading = true
      self.$http.put('/api/merchantCoal/issue', {ids: ids})
        .then(function (res) {
          self.syncLoading = false
          if (self.$refs[index]) {
            self.$refs[index].doClose()
          }
          self.crud.submitSuccessNotify()
          self.crud.toQuery()
        }).catch(function (error) {
          self.syncLoading = false
          if (self.$refs[index]) {
            self.$refs[index].doClose()
          }
        })
    },
    selectMineMouthName (val) {
      let self = this
      if (!val){
        self.coalType = []
        self.coalValueData.mineMouthId = null
        self.coalValueData.coalCategoryId = null
        self.coalValueData.coalName = null
        self.form.coalCategoryName = null
        self.form.coalCategoryId = null
        self.coalName = []
        self.form.mineMouthName = null
        self.form.coalName = null
        self.coalData = null
        return
      }
      let obj = {}
      obj = self.options.find((item) => {
        return item.id === val
      })
      self.form.mineMouthName = obj.mineMouthName
      self.$http.get('api/coal/findCoalInfo?id='+ val).then(function (res) {
        self.coalType = res
        self.coalName = []
        self.coalData = null
        self.coalValueData.coalCategoryId = null
        self.coalValueData.coalCategoryName = null
        self.coalValueData.coalName = null
        self.form.coalCategoryName = null
        self.form.coalCategoryId = null
        self.form.coalName = null
      }).catch(function (error) {
        console.log(error)
      })
    },
    selectCategoryCode (mineMouthId,coalCategoryId) {
      let self = this
      if (!coalCategoryId){
        self.coalName = []
        self.coalData = null
        self.coalValueData.coalCategoryId = null
        self.coalValueData.coalName = null
        self.form.coalCategoryName = null
        self.form.coalCategoryId = null
        self.form.coalName = null
        return
      }
      let obj = {}
      obj = self.coalType.find((item) => {
        return item.coalCategoryId === coalCategoryId
      })
      self.form.coalCategoryName = obj.coalCategoryName
      self.form.coalCategoryId = coalCategoryId
      self.$http.get('api/coal/findCoalCategoryCode?mineMouthId='+ mineMouthId + '&coalCategoryId=' +coalCategoryId).then(function (res) {
        self.coalName = res
        self.coalData = null
        self.coalValueData.coalName = null
        self.form.coalName = null
      }).catch(function (error) {
        console.log(error)
      })
    },
    selectCategoryCodeName (mineMouthId,coalCategoryId,name) {
      let self = this
      if (!name){
        self.coalData = null
        self.form.coalName = null
        return
      }
      self.form.coalName = name
      self.$http.get('api/coal/findCoalCategoryCodeName?mineMouthId='+ mineMouthId + '&coalCategoryId=' +coalCategoryId + '&name=' + name).then(function (res) {
        if (self.form.id){
          self.form.coalId = res.coalId
        }else {
          self.form = res
          self.form.coalName = name
          self.coalData = JSON.parse(JSON.stringify(res))
        }
      }).catch(function (error) {
        console.log(error)
      })
    },
    selectCoalTechnology (val) {
      let obj = {}
      obj = this.coalTechnology.find((item) => {
        return item.ecode === val
      })
      this.form.coalTechnologyName = obj.cname
    },
    update1(val) {
      let self = this
      self.issue = val
      self.$refs['form'].validate((valid) => {
        if (valid) {
          self.$refs['upload1'].upload()
        }
      })
    },
    update() {
      let self = this
      self.$refs['form'].validate((valid) => {
        if (valid) {
          self.$refs['upload'].upload()
        }
      })
    },
    edit(value) {
      let self = this
      if (value) {
        self.selectMineMouthNameInfo(value.mineMouthId,value.coalCategoryId)
        self.coalData = null
        self.form = Object.assign({}, value)
        self.coalValueData = {mineMouthId: self.form.mineMouthId,coalCategoryId: self.form.coalCategoryId,coalName: self.form.coalName }
        self.crud.status.edit = CRUD.STATUS.PREPARED
        return
      }
      let updateData = self.crud.selections
      if (updateData.length > 1) {
        self.$message({
          message: '不能同时修改多行',
          type: 'warning'
        })
      } else if (updateData.length < 1) {
        self.$message({
          message: '请选择一行数据',
          type: 'warning'
        })
      } else {
        self.selectMineMouthNameInfo(updateData[0].mineMouthId, updateData[0].coalCategoryId)
        self.coalData = null
        self.form = Object.assign({}, updateData[0])
        self.coalValueData = { mineMouthId: self.form.mineMouthId,coalCategoryId: self.form.coalCategoryId,coalName: self.form.coalName }
        self.crud.status.edit = CRUD.STATUS.PREPARED
      }
    },
    save() {
      let self = this
      self.$refs['form'].validate((valid) => {
        if (valid) {
          if (!self.coalValueData.coalName){
            self.$message({
              customClass:'zZindex',
              message: '名称不能为空',
              type: 'warning'
            })
            return
          }
          if (!self.coalValueData.coalCategoryId){
            self.$message({
              customClass:'zZindex',
              message: '煤种不能为空',
              type: 'warning'
            })
            return
          }
          self.form.coalInfo = []
          if (self.baseCates){
            for( var base in self.baseCates) {
              let key = self.baseCates[base].ecode
              let name = self.baseCates[base].cname
              if (self.form.coalInfos && self.form.coalInfos[key]){
                self.form.coalInfo.push({"key": key,"name":name,"value": self.form.coalInfos[key]})
              }else {
                self.form.coalInfo.push({"key": key,"name":name,"value": null})
              }
            }
          }
          if (self.$refs['upload'].uploadItem[0]){
            if (self.$refs['upload'].uploadItem[0].objKey){
              self.form.laboratoryBillPic = self.$refs['upload'].imgValue + self.$refs['upload'].uploadItem[0].objKey
            }
          }
          if (self.$refs['upload1'].uploadItem[0]){
            if (self.$refs['upload1'].uploadItem[0].objKey){
              self.form.coalPic = self.$refs['upload1'].imgValue + self.$refs['upload1'].uploadItem[0].objKey
            }
          }
          self.form.priceUnit = self.priceUnit
          self.form.coalName = self.coalValueData.coalName
          self.form.mineMouthId = self.coalValueData.mineMouthId
          self.form.coalCategoryId = self.coalValueData.coalCategoryId
          self.form.falg = self.issue
          if (!self.form.id) {
            self.$http.post('api/merchantCoal', self.form).then(function (res) {
              self.crud.status.add = 0
              self.crud.resetForm()
              self.crud.addSuccessNotify()
              self.crud.toQuery()
            }).catch(function (error) {
              console.log(error)
            })
          } else {
            self.$http.put('api/merchantCoal', self.form).then(function (res) {
              self.crud.status.edit = 0
              self.crud.resetForm()
              self.crud.editSuccessNotify()
              self.crud.toQuery()
            }).catch(function (error) {
              console.log(error)
            })
          }

        }
      })
    },
    add() {
      let self = this
      self.coalValueData = {}
      self.coalData = null
      self.form = {coalInfos: [],coalInfo: []}
      self.crud.status.add = CRUD.STATUS.PREPARED
    },
    del(data) {
      let self = this
      self.$confirm(`确定删除这条数据, 是否继续？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        self.crud.doDelete(data)
       /* let parm = {
          ids: [data.id]
        }
        self.$http.delete('/api/commodity/', parm).then(function(value) {
          if (value.ok) {
            this.crud.notify('刪除成功', CRUD.NOTIFICATION_TYPE.WARNING)
            this.crud.toQuery()
          }
        })*/
      }).catch(() => {
      })
    },
    // 改变状态
    changeEnabled(data) {
      this.$confirm('确定删除这条数据, 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let parm = {
          ids: [data.id]
        }
        crudApp.updateStatus(parm).then(res => {
          this.crud.notify(data.isMandatory === 0 ? '强制更新' : '不强制更新', CRUD.NOTIFICATION_TYPE.SUCCESS)
          this.crud.toQuery()
        }).catch(() => {
          // data.dataStatus = !data.dataStatus
        })
      }).catch(() => {
        // data.dataStatus = !data.dataStatus
      })
    },
    operationSave(value) {
      let self = this
      self.operationLoading = true
      self.$http.put('/api/coalProducts/operation', self.operationValue)
          .then(function (res) {
            self.operationLoading = false
            self.operationVisible = false
            self.operationValue = {}
            self.crud.toQuery()
          }).catch(function (error) {
        self.operationLoading = false
      })
    },
    operation(datas) {
      let self = this
      let updateData = datas
      if (updateData.length > 1) {
        self.$message({
          message: '不能同时操作多行',
          type: 'warning'
        })
      } else if (updateData.length < 1) {
        self.$message({
          message: '请选择一行数据',
          type: 'warning'
        })
      } else {
        self.operationValue = {
          id: updateData[0].id,
          isShow: updateData[0].isShow,
          sort: updateData[0].sort,
          level: updateData[0].level
        }
        self.operationVisible = true
      }
    },
    getCommSummaries({column, customer, title = '合计', titleIndex}) {
      this.$nextTick(() => {
        this.$refs['table'].doLayout()
      })
      return function(param) {
        const sums = []
        const {columns, data} = param
        columns.forEach((columnItem, index) => {
          if ((titleIndex === undefined && columnItem.type === 'index') || index === titleIndex) {
            sums[index] = title
          } else if (customer) {
            sums[index] = customer[columnItem.property] === null || customer[columnItem.property] === undefined || customer[columnItem.property] === '' ? ' ' : customer[columnItem.property]
          } else {
            let sumList = []
            column.forEach((e) => {
              if (e.toString().includes(' ')) {
                for (let i = Number(e.split(' ')[0]); i <= Number(e.split(' ')[1]); i++) {
                  sumList.push(i)
                }
              } else {
                sumList.push(Number(e))
              }
            })
            if (sumList.includes(index)) {
              debugger
              const values = data.map(e => Number(e[columnItem.property]))
              if (!values.every(value => isNaN(value))) {
                sums[index] = values.reduce((prev, curr) => {
                  const value = Number(curr)
                  if (!isNaN(value)) {
                    return prev + curr
                  } else {
                    return prev
                  }
                }, 0)
                sums[index] += ''
              } else {
                sums[index] = ' '
              }
            }
          }
        })
        return sums
      }
    },
    closeDialog(formName) {
      this.$refs[formName].resetFields();
    },
    objectKey(key,value){
      let keyValue={};
      keyValue[key]=value;
      return key;
    },
    getCategory() {
      let self = this
      self.$http.get("/api/baseCategory/getCateValue?key="+ "coal_info").then(function(value) {
        self.baseCates = value
      }).then(function(value) {
        self.$http.get("/api/baseCategory/getCateValue?key="+ "technology_coal").then(function(value) {
          self.coalTechnology = value
        })
      }).then(function(value) {
        self.$http.get("/api/param/getParamKey?key="+ "coal_unit").then(function(value) {
          self.priceUnit = value
        })
      })
    },
    selectMineMouthNameInfo(mineMouthId,coalCategoryId) {
      const self = this
      self.$http.get('api/coal/findCoalInfo?id='+ mineMouthId).then(function (res) {
        self.coalType = res
      }).then(function(res) {
        self.$http.get('api/coal/findCoalCategoryCode?mineMouthId='+ mineMouthId + '&coalCategoryId=' +coalCategoryId).then(function (res) {
          self.coalName = res
        }).catch(function(error) {
          console.log(error)
        })
      }).catch(function(error) {
        console.log(error)
      })
    },
    search() {
      const self = this
      self.$http.get("/api/coalCategory/query").then(function(value) {
        self.coalTypes = value
      })
      self.$http.get("/api/mineMouth/getMineMouth").then(function(value) {
        self.options = value
      })
      self.$http.get("/api/systemController/getMerchant").then(function(value) {
        if (value.ok){
          self.merchant = value.data
        }
      })
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    }
  },
  mounted: function() {
    this.tableHeight =  this.height - this.$refs.ele.clientHeight
    this.getCategory()
    this.search()
  },
}
</script>

<style scoped>

</style>
